package com.kxjlcc.testudp.ui

import android.annotation.SuppressLint
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import com.kxjlcc.testudp.R
import com.kxjlcc.testudp.udptool.UDPConnectListener
import com.kxjlcc.testudp.udptool.UDPTools
import kotlinx.android.synthetic.main.activity_main.*
import java.net.SocketAddress
import java.nio.charset.Charset

class MainActivity : AppCompatActivity() {
    private val log = "MainActivity"
    private lateinit var tools: UDPTools

    private val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                1 -> tools.receiveMsg()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tools = UDPTools("10.0.2.15", 8081, object : UDPConnectListener {
            override fun onConnect() {
                Log.d(log, "on connect")
                handler.sendEmptyMessage(1)
            }

            override fun onError() {
                Log.d(log, "on error")
            }

            override fun onReceiveMsg(remoteAddress: SocketAddress, message: String) {
                Log.d(log, "receive msg ,address is $remoteAddress,msg is $message")
            }

        })
        tools.connect("192.168.136.1", 8080)

        btn_send_data.setOnClickListener {
//            编码方式和服务端编码方式保持一致，才不会出现乱码的情况
            tools.sendMsg("192.168.136.1", 8080, "你好啊".toByteArray(Charset.forName("GBK")))
        }
    }

    override fun onStop() {
        super.onStop()
        tools.close()
    }
}
